﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Views;
using Common;

namespace DataAccess
{
    public class ShoppingCartRepository : ConnectionClass
    {
        public void AddToCart(ShoppingCart cart)
        {
            entities.AddToShoppingCarts(cart);
            entities.SaveChanges();
        }

        public void DeleteCart(int scID)
        {
            ShoppingCart sc = GetShoppingCartByID(scID);
            entities.ShoppingCarts.DeleteObject(sc);
            entities.SaveChanges();            
        }

        public int GetNoOfItemsInShoppingCart(string username)
        {
            if (entities.ShoppingCarts.Where(s => s.Username_FK == username).Count() == 0)
                return 0;
            else return entities.ShoppingCarts.Where(s => s.Username_FK == username).Sum(x => x.Quantity);
        }

        public int GetProductIDInShoppingCart(int productID)
        {
            if (entities.ShoppingCarts.Where(s => s.Product_FK == productID).Count() == 0)
                return 0;
            else return entities.ShoppingCarts.Where(s => s.Product_FK == productID).Sum(x => x.Quantity);
        }

        public ShoppingCart GetShoppingCartByID(int id)
        {
            return entities.ShoppingCarts.SingleOrDefault(sc => sc.ID == id);
        }

        public ShoppingCart ViewShoppingCart(string username)
        {
            return entities.ShoppingCarts.SingleOrDefault(sc => sc.Username_FK == username);
        }

        public IEnumerable<ShoppingCart> ListShoppingCart(string username)
        {
            return entities.ShoppingCarts.Where(sc => sc.Username_FK == username);
        }

        public IEnumerable<ShoppingCartView> DisplayShoppingCart(string username)
        {
            return (
              from s in entities.ShoppingCarts
              join pr in entities.Products on s.Product_FK equals pr.ID
              where s.Username_FK == username

              select new ShoppingCartView()
              {
                  ProductID = pr.ID,
                  ProductName = pr.Name,
                  Price = pr.Price * s.Quantity,
                  Quantity = s.Quantity
              }
              );
        }
    }
}
